'use strict';
angular.module('nec-admin.user')
    .controller('passwordController', ['$scope', '$state', 'authService', 'passwordService', 'sweetAlert',
        function ($scope, $state, authService, passwordService, sweetAlert) {
            $scope.password = {};
            $scope.focused = {
                oldPassword: false,
                newPassword: false,
                newPasswordConfirm: false
            };
            $scope.oldPasswordNotCorrect = false;
            $scope.passwordNotChanged = false;

            $scope.modifyPassword = function () {
                passwordService.modifyPassword($scope.password.old, $scope.password.new).then(function (resp) {
                    //修改密码成功
                    if (resp.status === 200) {
                        $scope.password.old = '';
                        $scope.password.new = '';
                        $scope.password.confirm = '';
                        authService.logout();
                        sweetAlert.confirm('修改密码成功, 请重新登录.', function () {
                            $state.go('login');
                        }, {
                            type: 'success',
                            showCancelButton: false
                        });
                    }
                    //修改密码失败
                    else {
                        sweetAlert.alert('由于喵星人的干扰, 修改密码失败', {type: 'error'});
                    }
                }, function (resp) {

                    switch (resp.status) {
                        case 400: //旧密码错误的状态码
                            $scope.oldPasswordNotCorrect = true;
                            angular.element('#oldPassword').focus();
                            break;
                        case 412: //新旧密码一致的状态码
                            $scope.passwordNotChanged = true;
                            angular.element('#newPassword').focus();
                            break;
                        default :
                            sweetAlert.alert('由于喵星人的干扰, 修改密码失败', {type: 'error'});
                            break;
                    }
                });
            };

            $scope.clear = function () {
                $scope.password.old = '';
                $scope.password.new = '';
                $scope.password.confirm = '';
                $scope.oldPasswordNotCorrect = false;
                $scope.passwordNotChanged = false;
                $scope.focused = {
                    oldPassword: false,
                    newPassword: false,
                    newPasswordConfirm: false
                };
            };
        }]);
